package com.woniuxy.producer.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 生产者发送消息可靠配置
 */
@Configuration
public class RabbitMQConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启消息的强制投递
        rabbitTemplate.setMandatory(true);
        // 消息到达交换机的确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback(){
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("消息数据 = " + correlationData);
                if (ack) {
                    System.out.println("消息到达了交换机");
                }else {
                    System.out.println("消息未到达交换机: " + cause);
                }
            }
        });
        return rabbitTemplate;
    }
}
